package logic

import (
	"context"
	"fmt"
	"month/model/mysql"
	"month/model/redis"
	"strconv"

	"month/shoprpc/internal/svc"
	"month/shoprpc/shoprpc"

	redis2 "github.com/go-redis/redis"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductsLikeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductsLikeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductsLikeLogic {
	return &ProductsLikeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductsLikeLogic) ProductsLike(in *shoprpc.ProductsLikeRequest) (*shoprpc.ProductsLikeResponse, error) {
	// todo: add your logic here and delete this line
	var product mysql.Products
	mysql.DB.Debug().Model(&mysql.Products{}).Where("id=?", in.Id).First(&product)
	if product.ID == 0 {
		return nil, fmt.Errorf("该条数据不存在")
	}
	i := product.Like + 1
	sli := mysql.Products{
		Like:   i,
		UserId: int(in.UserId),
	}

	err := mysql.DB.Debug().Model(&mysql.Products{}).Where("id=?", in.Id).Updates(&sli).Error
	if err != nil {
		return nil, fmt.Errorf("收藏失败")
	}

	redis.Rdb.ZAdd("productRank", redis2.Z{
		Score:  float64(i),
		Member: product.Name + strconv.Itoa(int(product.ID)),
	})

	return &shoprpc.ProductsLikeResponse{}, nil
}
